package com.shhic.hhplt.server.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
import com.shhic.hhplt.server.model.*;
import com.shhic.hhplt.server.mapper.ITestComplexQueryDao;
import com.shhic.hhplt.server.service.ITestComplexQueryService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.List;

@Service
@DS("hhpltTest")
@Transactional
public class TestComplexQueryServiceImpl implements ITestComplexQueryService {
    @Autowired
    private ITestComplexQueryDao tcxqDao;
    @Autowired
    private MongoCollection<Document> collection;

    @Override
    public List<BindingCodeQueryResult> queryBindingCodeCollection(
            BindingCodeQuery query) {
        List<String> codeNameList=query.getBindingCodeNameList();
        List<BindingCodeQueryResult> resultList=new ArrayList<>();
        FindIterable<Document> oriResult = collection.find(
                Filters.and(Filters.gte(query.getConditionCodeName(), query.getStartCode())
                        , Filters.lte(query.getConditionCodeName(), query.getEndCode()))
        ).projection(
                Projections.exclude(MongoConstantName.productName,MongoConstantName.createTime,MongoConstantName.updateTime)
        );
        if(oriResult.first()!=null){
            oriResult=oriResult.sort(Sorts.ascending(query.getConditionCodeName()));
        }else{
            return resultList;
        }
        for (Document d : oriResult) {
            BindingCodeQueryResult codeQuery=new BindingCodeQueryResult();
            codeQuery.setIdCode(d.getString(MongoConstantName.idCode));
            codeQuery.setQueryCode(d.getString(query.getConditionCodeName()));
            for (int i = 0; i < codeNameList.size(); i++) {
                codeQuery.setCode(i,d.getString(codeNameList.get(i)));
            }
            resultList.add(codeQuery);
        }
        return resultList;
    }


    @Override
    public List<WorkbayStatisticResultDb> queryWorkbayStatistic(
            WorkbayStatisticQuery query) {
        return tcxqDao.queryWorkbayStatistic(query);
    }

    @Override
    public List<ExportedTestReport> exportTestReports(long startTime, long endTime) {
        return tcxqDao.exportTestReports(startTime,endTime);
    }
}
